package com.spzx.cart.service.impl;

import com.spzx.cart.api.RemoteUpdateCartPrice;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.CartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteGetSkuPriceList;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: CartServiceImpl
 * Description:
 *
 * @Author linz
 * @Creat 2025/3/17 19:14
 * @Version 1.00
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteGetSkuPriceList remoteGetSkuPriceList;
    @Autowired
    private RemoteUpdateCartPrice remoteUpdateCartPrice;



    /**
     * 生成不同用户的购物车key
     * @param userId
     * @return
     */
    private String getCartKey(Long userId) {
        return "user:cart:" + userId;
    }


    /**
     * 添加商品到购物车
     * @param skuId
     * @param skuNum
     */
    @Override
    public void addToCart(Long skuId, Integer skuNum) {

        //1.获取登录用户id
        Long userId = SecurityContextHolder.getUserId();
        //2.生成用户对应的购物车key
        String cartKey = getCartKey(userId);
        //3.创建用户购物车Hash结构key BoundHashOps 是一个绑定到特定 Redis Key 的操作对象。
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        //4.判断当前商品是否在购物车中
        if (hashOps.hasKey(skuId.toString())) {
            //5.如果存在，更新数量
            CartInfo cartInfo = hashOps.get(skuId.toString());

            //判断当前种类商品加上添加到购物车的数量是否大于99，如果大于按照99来算
            if (cartInfo.getSkuNum() + skuNum > 99) {
                cartInfo.setSkuNum(99);
            }else {
                cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            }
            hashOps.put(skuId.toString(), cartInfo);
        } else {
            //6.如果不存在，添加到购物车
            //判断购物车的商品种类是否大于50件
            if (hashOps.size() >= 50) {
                throw new ServiceException("购物车商品种类不能超过50种");
            }else {

                //远程调用(需要经过InnerAuthAspect 检查键值为SecurityConstants.FROM_SOURCE的值是否为INNER)
                R<ProductSkuVo> productSkuResult = remoteProductService.getProductSku(skuId,SecurityConstants.INNER);
                //远程调用失败
                if (R.FAIL == productSkuResult.getCode()) {
                    throw new ServiceException("远程调用失败");
                }
                //远程调用成功
                ProductSkuVo productSkuVo = productSkuResult.getData();

                //组装购物车对象
                CartInfo cartInfo = new CartInfo();
                cartInfo.setUserId(userId);
                cartInfo.setSkuId(skuId);
                cartInfo.setSkuName(productSkuVo.getSkuName());
                cartInfo.setThumbImg(productSkuVo.getThumbImg());
                cartInfo.setCartPrice(productSkuVo.getSalePrice());
                cartInfo.setSkuPrice(productSkuVo.getSalePrice());
                cartInfo.setIsChecked(1);
                cartInfo.setCreateTime(new Date());
                cartInfo.setSkuNum(skuNum);

                hashOps.put(skuId.toString(), cartInfo);
            }

        }
    }

    /**
     * 获取购物车列表
     * @return
     */
    @Override
    public List<CartInfo> getCartList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);

        //远程调用批量更新商品实时价格
        this.updateCartPrice();
        //从redis中查询用户的购物车数据
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOps.values();
        if(!CollectionUtils.isEmpty(cartInfoList)){
            List<CartInfo> infoList = cartInfoList.stream()
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())) //时间降序排序
                    .collect(Collectors.toList());
            return infoList;
        }


        return new ArrayList<>();
    }

    /**
     * 删除购物车商品
     * @param skuId
     */
    @Override
    public void deleteCart(Long skuId) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);

        //从redis中查询用户的购物车数据
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        hashOps.delete(skuId.toString());
    }

    /**
     * 更新选中状态
     * @param skuId
     * @param isChecked
     */
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        //从redis中查询用户的购物车数据
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        if(hashOps.hasKey(skuId.toString())){
            CartInfo cartInfo = hashOps.get(skuId.toString());
            cartInfo.setIsChecked(isChecked);
            //更新缓存
            hashOps.put(skuId.toString(), cartInfo);
        }
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        redisTemplate.delete(cartKey);
    }

    /**
     * 全选购物车
     * @param isChecked
     */
    @Override
    public void allCheckCart(Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOps.values();
        for (CartInfo cartInfo : cartInfoList) {
            cartInfo.setIsChecked(isChecked);
            hashOps.put(cartInfo.getSkuId().toString(), cartInfo);
        }
    }

    /**
     * 查询用户购物车列表中选中商品列表
     * @return
     */
    @Override
    public List<CartInfo> getCartCheckedList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOps.values();
/*        ArrayList<CartInfo> cartCheckedList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {
            if(cartInfo.getIsChecked()==1){
                cartCheckedList.add(cartInfo);
            }
        }*/
        //优化后 集合流
        if(!CollectionUtils.isEmpty(cartInfoList)){
            cartInfoList = cartInfoList.stream()
                    .filter(cartInfo -> cartInfo.getIsChecked()==1)
                    .toList();
        }
        return cartInfoList;
    }

    /**
     * 删除购物车选中商品
     * @param userId
     * @return
     */
    @Override
    public Boolean deleteCartCheckedList(Long userId) {
        List<CartInfo> cartCheckedList = getCartCheckedList();
        if(CollectionUtils.isEmpty(cartCheckedList)){
            return false;
        }
        for (CartInfo cartInfo : cartCheckedList) {
            Long skuId = cartInfo.getSkuId();
            deleteCart(skuId);
        }
        return true;
    }

    /**
     * 更新购物车商品列表价格
     * @return
     */
    @Override
    public Boolean updateCartPrice() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);

        List<CartInfo> cartInfoList = hashOps.values();
        if(CollectionUtils.isEmpty(cartInfoList)){
            return false;
        }
        List<Long> skuIdList = cartInfoList.stream().map(CartInfo::getSkuId).toList();
        R<List<SkuPriceVo>> skuPriceListResult = remoteGetSkuPriceList.getSkuPriceList(skuIdList, SecurityConstants.INNER);

        if (R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException("远程调用失败："+skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();

        //比较购物车商品价格和最新价格
        Map<Long, BigDecimal> skuPriceVoMap = skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        for (CartInfo cartInfo : cartInfoList) {
            BigDecimal skuPrice = skuPriceVoMap.get(cartInfo.getSkuId());
            //如果价格发生变化，则更新购物车价格
            if (skuPrice.compareTo(cartInfo.getSkuPrice()) != 0){
                cartInfo.setSkuPrice(skuPrice);
                hashOps.put(cartInfo.getSkuId().toString(), cartInfo);
            }
        }
        return true;
    }

}
